<?php


namespace App\Http\Controllers\api\shop;


use App\Http\Controllers\api\base\BaseController;
use App\Models\shop\ChinaArea;
use App\Models\shop\Shop;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ShopController extends BaseController
{
    public function cityList()
    {
        $province_id = Shop::groupBy('province_id')->remember(Carbon::now()->addSeconds(60))->pluck('province_id');

        $city_id = Shop::groupBy('city_id')->remember(Carbon::now()->addSeconds(60))->pluck('city_id');

        $district_id = Shop::groupBy('district_id')->remember(Carbon::now()->addSeconds(60))->pluck('district_id');

        $province = ChinaArea::whereIn('code',$province_id)->remember(Carbon::now()->addSeconds(60))->get();

        $city = ChinaArea::whereIn('code',$city_id)->remember(Carbon::now()->addSeconds(60))->get();

        $district = ChinaArea::whereIn('code',$district_id)->remember(Carbon::now()->addSeconds(60))->get();

        $rows = [];

        foreach ($province as $k => $v){
            $arr = [];
            $arr['id'] = $v['id'];
            $arr['name'] = $v['name'];
            $arr['items'] = [];
            
            foreach ($city as $key =>  $item){
                if ($item['parent_id'] == $v['id']){
                    $arr['items'][$key] = [
                        'id' => $item['id'],
                        'name' => $item['name']
                    ];

                    $items = [];

                    foreach ($district as $i => $x){
                        if ($x['parent_id'] == $item['id']){
                            $items[] =  [
                                'id' => $x['id'],
                                'name' => $x['name']
                            ];
                        }

                    }
                    $arr['items'][$key]['items'] = $items;

                }
            }
            $rows[] = $arr;
        }

        return success($rows);
    }


    public function shopList(Request $request)
    {
        $map = [];

        if (isInt($request->province_id)){
            $map['province_id'] = $request->province_id;
        }

        if (isInt($request->city_id)){
            $map['city_id'] = $request->city_id;
        }

        if (isInt($request->district_id)){
            $map['district_id'] = $request->district_id;
        }

        $rows = Shop::where($map)->remember(Carbon::now()->addSeconds(60))->get();

        return success($rows);

    }

    /**
     * 获取地区信息
     */
    public function getArea(Request $request)
    {
        if (!$request->id){
            $map['parent_id'] = 1;
        }else{
            $map['parent_id'] = $request->id;
        }

        $rows = ChinaArea::where($map)->select(['id','name','parent_id'])->get();

        return success($rows);

    }

    
}